import { GenerateServiceProps } from '@umijs/openapi';

/**
 * 自定义接口文件夹名称
 */
export const customClassName = (type: string, tagName: string) => {
  return tagName;
};

/**
 * 自定义文件名
 * 如果有path: path
 * 如果有operationId: 模块名称(path路由第一位)+方法名
 */
export const customFunctionName: NonNullable<GenerateServiceProps['hook']>['customFunctionName'] = (
  api
) => {
  const path = api.path || '';

  const genByPath = (path: string) => {
    return path
      .replace(/[-_]/g, '/')
      .split('/')
      .filter(Boolean)
      .map((v, i) => (i > 0 ? v.charAt(0).toUpperCase() + v.slice(1) : v))
      .join('');
  };

  if (path.length && !/\{.*\}/.test(path)) {
    return genByPath(path);
  }

  if (api.operationId) {
    const operationId = api.operationId;

    if (path) {
      // 模块名+方法名
      return `${path.split('/').filter(Boolean)[0]}${operationId
        .charAt(0)
        .toUpperCase()}${operationId.slice(1)}`;
    }

    return operationId;
  }

  throw new Error('接口格式错误');
};
